import sys
import os
import yaml
from pathlib import Path
from tqdm import tqdm
import librosa
import argparse

# 将 根目录添加到 Python 路径中
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# 导入路径管理器和模块
from src.utils import CONFIG_PATH, DATABASE_PATH, MUSIC_LIBRARY_PATH
from src.database import Database
from src.fingerprinting.processor import Processor
from src.fingerprinting.hashing import Hasher

def fingerprint_library(music_dir: Path, config_path: Path, db_path: Path, no_duplicate_check: bool):
    """
    使用确定的绝对路径对音乐库进行指纹识别。


    Args:
        music_dir: Path to the directory containing music files.
        config_path: Path to the YAML configuration file.
        db_path: Path to the SQLite database file.
        no_duplicate_check: If True, skips checking for duplicate songs.
    """
    # 加载配置
    with open(config_path, 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f)

    # 初始化模块
    db = Database(str(db_path))
    processor = Processor(config)
    hasher = Hasher(config['hashing'])

    # 扫描音频文件
    audio_files = list(music_dir.glob('*.wav')) + list(music_dir.glob('*.mp3'))
    if not audio_files:
        print(f"No audio files (.wav, .mp3) found in '{music_dir}'.")
        return

    print(f"Found {len(audio_files)} songs in '{music_dir}' to fingerprint.")

    # 遍历并处理
    with db:
        for audio_file in tqdm(audio_files, desc="Fingerprinting songs"):
            try:
                duration = librosa.get_duration(path=str(audio_file))
                skip_check = no_duplicate_check

                # Add song to the database
                song_id = db.add_song(
                    name=audio_file.stem,
                    file_path=str(audio_file.resolve()),
                    duration=int(duration),
                    config=config,
                    skip_duplicate=skip_check
                )

                # 如果歌曲是重复的，song_id 会是 None，此时跳过后续处理
                if song_id is None:
                    continue

                peaks = processor.audio_to_peaks(str(audio_file))
                if not peaks.any():
                    tqdm.write(f"Warning: No peaks found for {audio_file.name}. Skipping.")
                    continue

                fingerprints = hasher.peaks_to_fingerprints(peaks)
                if not fingerprints:
                    tqdm.write(f"Warning: Could not generate fingerprints for {audio_file.name}. Skipping.")
                    continue

                fingerprints_to_add = [(song_id, h, t) for h, t in fingerprints]
                db.add_fingerprints(fingerprints_to_add)

            except Exception as e:
                tqdm.write(f"ERROR processing {audio_file.name}: {e}")

    print("\nFingerprinting complete!")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Fingerprint a directory of audio files.")
    parser.add_argument(
        '--dir',
        type=Path,
        default=MUSIC_LIBRARY_PATH,
        help=f"Directory containing music files. Default: {MUSIC_LIBRARY_PATH}"
    )
    parser.add_argument(
        '--no-duplicate-check',
        action='store_true',
        help="Disable checking for duplicate songs to speed up the process."
    )
    args = parser.parse_args()

    fingerprint_library(args.dir, CONFIG_PATH, DATABASE_PATH, args.no_duplicate_check)
